<template>
  <div class="main_app">
    <el-collapse v-model="collapseActiveName" accordion>
      <el-collapse-item v-for="(type_obj,type_obj_idx) in siteTypes" :key="type_obj_idx" :name="type_obj.key" :title='type_obj.key'>
        <div>
          <div v-for="(i,idx) in type_obj.list" class="url-item display-flex algin-items-center"
            :key="idx">
            <el-tag class="mx-1" type="warning" effect="dark" round>
              {{ idx+1 }}
            </el-tag>
            <div style="margin-left:5px">{{type_obj.key!='gpt3'?i.site_title:'gpt3'}}</div>
            <div style="margin-left:5px" v-if="type_obj.key!='gpt3'">{{i.site_url}}</div>
            <div style="margin-left:auto">
              <el-button type="success" round @click="toLink(i)">访问</el-button>
            </div>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item name="custom" title='custom'>
        <div class="display-flex algin-items-center" style="width:100%">
          <div style="width: 100%;">
            <el-input v-model="baseUrl" placeholder="轻输入后台请求地址" />
          </div>
          <div style="margin-left:10px">
            <el-button type="primary" @click="changeBaseUrl">确 定</el-button>
          </div>
        </div>
        <el-divider content-position="left">配置填充列表</el-divider>
        <div>
          <div style="margin:10rpx"><el-button type="primary" round
              @click="addHandle">新增</el-button>
          </div>
          <div style="margin: 10px;max-height:400px;overflow: auto;">
            <div v-if="addShow" style="margin:10px">
              <div>
                <el-form ref="addFormRef" :rules="rules" :label-position="'left'"
                  label-width="100px" :model="curForm">
                  <el-form-item prop="url" label="链接地址">
                    <el-input v-model="curForm.url" placeholder="全部可以用'*'" />
                  </el-form-item>
                  <el-form-item prop="captchaPath" label="验证码定位">
                    <el-input v-model="curForm.captchaPath" />
                  </el-form-item>
                  <el-form-item prop="inputPath" label="输入框定位">
                    <el-input v-model="curForm.inputPath" />
                  </el-form-item>
                  <el-form-item prop="buttonPath" label="按钮定位">
                    <el-input v-model="curForm.buttonPath" />
                  </el-form-item>
                </el-form>
              </div>
              <div style="margin:10px">
                <el-button type="primary" round
                  @click="addConfirm(curForm,addFormRef)">确定</el-button>
                <el-button type="default" round @click="cancel">取消</el-button>
              </div>
            </div>
            <div v-for="(i,idx) in urlList" :key="idx" style="">
              <div class="url-item display-flex algin-items-center">
                <el-tag class="mx-1" type="warning" effect="dark" round>
                  {{ idx+1 }}
                </el-tag>
                <div style="margin-left:3px">{{i.url}}</div>
                <div style="margin-left:auto">
                  <el-button type="success" round @click="updateHandle(i)">修改</el-button>
                </div>
              </div>
              <div v-if="curForm.id==i.id" style="margin:10px">
                <div>
                  <el-form ref="updateFormRef" :rules="rules" :label-position="'left'"
                    label-width="100px" :model="curForm">
                    <el-form-item prop="url" label="链接地址">
                      <el-input v-model="curForm.url" placeholder="全部可以用'*'" />
                    </el-form-item>
                    <el-form-item prop="captchaPath" label="验证码定位">
                      <el-input v-model="curForm.captchaPath" />
                      <el-tag @click="selectEle(curForm,'captchaPath')">选择元素</el-tag>
                    </el-form-item>
                    <el-form-item prop="inputPath" label="输入框定位">
                      <el-input v-model="curForm.inputPath" />
                      <el-tag @click="selectEle(curForm,'inputPath')">选择元素</el-tag>
                    </el-form-item>
                    <el-form-item prop="buttonPath" label="按钮定位">
                      <el-input v-model="curForm.buttonPath" />
                      <el-tag @click="selectEle(curForm,'buttonPath')">选择元素</el-tag>
                    </el-form-item>
                  </el-form>
                </div>
                <div style="margin:10px">
                  <el-button type="primary" round
                    @click="updateConfirm(curForm,updateFormRef)">确定</el-button>
                  <el-button type="default" round @click="cancel">取消</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>

  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from "vue";
import * as _ from "lodash";
import axios from "axios";
const generateUniqueId = () => {
  const timestamp = Date.now();
  const randomNum = Math.random() * Math.pow(10, 17);
  const uniqueId = `${timestamp}-${randomNum}`;
  return uniqueId;
};
const siteTypes = ref([
  { key: "bing_ai", list: [] },
  { key: "gpt3", list: [] },
  { key: "gemini", list: [] },
  { key: "claude", list: [] },
  { key: "gpt4_plus", list: [] },
  { key: "chat_academic", list: [] },
  { key: "stable_diffusion", list: [] },
]);
siteTypes.value.map((obj) => {
  
  if (obj.key == "gpt3") {
    let config = {
      method: "get",
      url: `https://ai-box.cn:5080/api_v3/getFreeSiteByRandom`,
      headers: {
        Accept: "application/json, text/plain, */*",
      },
    };
    axios(config)
      .then((res) => {
        if (res.data.data) {
          obj.list = [{...res.data.data,site_title:res.data.data.site_url}];
        }
      })
      .catch(function (error) {
        console.log(error);
      });

  } else {
    let config = {
      method: "get",
      url: `https://ai-box.cn:5080/api_v3/fetchSiteListByType?page_id=0&page_size=30&site_type=${obj.key}`,
      headers: {
        Accept: "application/json, text/plain, */*",
      },
    };
    axios(config)
      .then((res) => {
        if (res.data.data) {
          obj.list = res.data.data;
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  }
});
const formKey = ref("");
const addFormRef = ref();
const updateFormRef = ref();
const baseUrl = ref("");
const addShow = ref(false);
const curForm = ref({});
const collapseActiveName = ref("Bing");
const toLink = (e) => {
  window.open(e.site_url);
};
const selectEle = async (curForm, key) => {
  formKey.value = key;
  console.log(key, "key");

  // document.body.style.display = "none";
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  chrome.scripting
    .executeScript({
      target: { tabId: tab.id },
      function: async (key) => {
        return await new Promise((resolve) => {
          let dict = {
            captchaPath: "img",
            inputPath: "input",
            buttonPath: "button",
          };
          var getXPathForElement = (element) => {
            const allNodes = document.getElementsByTagName("*");
            for (
              let segs = [];
              element && element.nodeType === 1;
              element = element.parentNode
            ) {
              if (element.hasAttribute("id")) {
                let uniqueIdCount = 0;
                for (let n = 0; n < allNodes.length; n++) {
                  if (
                    allNodes[n].hasAttribute("id") &&
                    allNodes[n].id === element.id
                  )
                    uniqueIdCount++;
                  if (uniqueIdCount > 1) break;
                }
                if (uniqueIdCount === 1) {
                  segs.unshift(`id("${element.getAttribute("id")}")`);
                  return segs.join("/");
                } else {
                  segs.unshift(
                    `${element.localName.toLowerCase()}[@id="${element.getAttribute(
                      "id"
                    )}"]`
                  );
                }
              } else {
                let xPathIndex = 1;
                for (
                  let sibling = element.previousSibling;
                  sibling;
                  sibling = sibling.previousSibling
                ) {
                  if (
                    sibling.nodeType === 1 &&
                    sibling.localName === element.localName
                  )
                    xPathIndex++;
                }
                const tagName = element.localName.toLowerCase();
                const nthChild = `[${xPathIndex}]`;
                segs.unshift(`${tagName}${nthChild}`);
              }
            }
            return segs.length ? `/${segs.join("/")}` : null;
          };

          const allowElements = [...document.querySelectorAll(dict[key])];
          let mouseoverHandler = (event) => {
            event.target.style.border = "1px dashed #000";
            event.target.addEventListener("mouseout", mouseoutHandler);
          };
          let mouseoutHandler = (event) => {
            event.target.style.border = "none";
          };
          allowElements.forEach((ele) => {
            let clickHandler = (event) => {
              allowElements.forEach((i) => {
                i.style.border = "none";
                i.removeEventListener("mouseover", mouseoverHandler);
                i.removeEventListener("mouseout", mouseoutHandler);
                i.removeEventListener("click", clickHandler);
              });
              xpath = getXPathForElement(event.target);
              resolve(xpath);
            };
            ele.addEventListener("mouseover", mouseoverHandler);
            ele.addEventListener("click", clickHandler);
          });
        }).then((res) => {
          console.log(res, "xpath");
          return res;
        });
      },
      args: [key],
    })
    .then((res) => {
      if (res) {
        let curTabRes = res[0].result;
        // document.body.style.display = "auto";
        console.log(curForm, key, "curForm.value");
        curForm[formKey.value] = curTabRes;
      }
    });
};
const rules = reactive({
  url: [{ required: true, message: "请输入url", trigger: "blur" }],
  captchaPath: [
    { required: true, message: "请输入验证码定位", trigger: "blur" },
  ],
  inputPath: [{ required: true, message: "请输入输入框定位", trigger: "blur" }],
});
const addHandle = () => {
  curForm.value = {};
  curForm.value.id = generateUniqueId();
  addShow.value = true;
};

const updateHandle = (e) => {
  addShow.value = false;
  curForm.value = _.cloneDeep(e);
};

const addConfirm = async (curForm, ref) => {
  console.log(ref, "ref");
  await ref.validate((valid, fields) => {
    if (valid) {
      urlList.value.unshift(curForm);
      cancel();
    } else {
      console.log("error submit!", fields);
    }
  });
};
const updateConfirm = async (curForm, ref) => {
  console.log(ref[0].validate, "ref");
  await ref[0].validate((valid, fields) => {
    if (valid) {
      let curItemIdx = urlList.value.findIndex((i) => i.id == curForm.id);
      urlList.value.splice(curItemIdx, 1, curForm);
      cancel();
    } else {
      console.log("error submit!", fields);
    }
  });
};
const cancel = () => {
  curForm.value = {};
  addShow.value = false;
};

const urlList = ref([
  {
    id: "1231235345312",
    url: "http://localhost:9990/#/PaymentPlan",
    captchaPath: "",
    inputPath: "",
  },
  {
    id: "1231235345315",
    url: "http://localhost:9990/#/PaymentPlan",
    captchaPath: "",
    inputPath: "",
  },
  {
    id: "1231235345319",
    url: "http://localhost:9990/#/PaymentPlan",
    captchaPath: "",
    inputPath: "",
  },
  {
    id: "1231235345320",
    url: "http://localhost:9990/#/PaymentPlan",
    captchaPath: "",
    inputPath: "",
  },
  {
    id: "1231235345338",
    url: "http://localhost:9990/#/PaymentPlan",
    captchaPath: "",
    inputPath: "",
  },
]);
watch(urlList.value, (val) => {
  // window.localStorage.setItem("h_x_auto_list", urlList.value);
  chrome.runtime.sendMessage(
    {
      action: "updateStorage",
      data: { key: "h_x_auto_list", val: urlList.value },
    },
    function (response) {
      console.log("Response from background.js:", response);
    }
  );
});
const changeBaseUrl = () => {
  // window.localStorage.setItem("h_x_base_url", baseUrl.value);
  chrome.runtime.sendMessage(
    {
      action: "updateStorage",
      data: { key: "h_x_base_url", val: baseUrl.value },
    },
    function (response) {
      console.log("Response from background.js:", response);
    }
  );
};
</script>

<style>
.main_app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  width: 500px;
}
.display-flex {
  display: flex;
}
.algin-items-center {
  align-items: center;
}
.url-item {
  border-radius: 5px;
  background: #4d97d8;
  padding: 10px;
  color: #fff;
  margin-bottom: 5px;
}
.hx-hover {
  position: relative;
}
.hx-hover::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 2px dashed #8149c1;
  background-color: rgba(28, 112, 237, 0.5); /* 这里设置遮罩的颜色和透明度 */
}
</style>



